package br.com.projeto.web.vraptor.interceptors;

import java.util.ArrayList;
import java.util.List;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.view.Results;
import br.com.projeto.web.vraptor.componentes.SessionUser;
import br.com.projeto.web.vraptor.controllers.MainController;

@Intercepts
public class AcessInterceptor implements Interceptor {

	private static List<String> methods;

	//Lista de actions permitidas
	static {
		methods = new ArrayList<String>();
		methods.add("MainController.form");
		methods.add("MainController.login");
		methods.add("MainController.logout");
		methods.add("MobileController.listarAtividades");
	}

	private SessionUser session;
	private Result result;

	public AcessInterceptor(SessionUser session, Result result) {
		this.session = session;
		this.result = result;
	}

	@Override
	public boolean accepts(ResourceMethod method) {

		return !methods.contains(method.getMethod().getDeclaringClass()
				.getSimpleName()
				+ "." + method.getMethod().getName());
	}

	@Override
	public void intercept(InterceptorStack stack, ResourceMethod method,
			Object instance) throws InterceptionException {

		System.out.println("Interceptando -> "
				+ method.getMethod().getDeclaringClass().getSimpleName() + "."
				+ method.getMethod().getName());

		if (this.session.getUsuario() == null)
			result.use(Results.logic()).redirectTo(MainController.class).login();
		else
			stack.next(method, instance);
	}

}
